<template>
    <van-nav-bar title="拼团详情" left-text="" left-arrow @click-left="goBack" />

    <!-- 进度条 -->
    <div class="box">
        <van-circle v-model:current-rate="currentRate" :rate="currentRate" :speed="100" :text="text" size="200px"
            :color="gradientColor" />
    </div>

    <!-- 拼团时间 -->
    <div class="box_time">
        <van-count-down :time="time" format="HH 时 mm 分 ss 秒" />
    </div>

    <!-- 拼团信息 -->
    <van-card :price="info.buy_text" :thumb="info.product.thumbs_text">
        <template #title>
            <h3>{{ info.product.name }}</h3>
            <div> 人数： <span style="color: red;">{{ info.total }}</span>人 </div>
            <div> 拼团时间：{{ info.createtime }} (开始) ~ {{ info.endtime_text }} (结束)</div>
        </template>
    </van-card>

    <!-- 发起人 -->
    <div class="item" v-for="(item, index) in teamlist" :key="item.id">
        <van-image width="50px" height="50px" fit="cover" :src="item.business.avatar_text" />
        <div class="info">
            <div class="nickname" v-if="index == 0">{{ item.business.nickname }} (发起人)</div>
            <div class="nickname" v-else>{{ item.business.nickname }}</div>
            <div class="time">拼单时间：{{ item.createtime }}</div>
        </div>
    </div>
    <div class="actions">
        <van-button type="danger" size="large" @click="getProductInfoData">参与拼团</van-button>
    </div>

    <!-- 商品SKU -->
    <van-sku v-model="SkuShow" ref="SkuRef" stepper-title="购买数量" :sku="sku" :goods="goods" :goods-id="proid"
        :properties="properties">
        <!-- 自定义 sku actions -->
        <template #sku-actions="">
            <div class="van-sku-actions">
                <van-button square size="large" type="danger" @click="teamJoin">
                    参与拼团
                </van-button>
            </div>
        </template>
    </van-sku>
</template>

<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css'

const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.push('/team/index') }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ?? {})
const teamid = proxy.$route.query.teamid ? proxy.$route.query.teamid : 0;

const gradientColor = {
    '0%': '#3fecff',
    '100%': '#6149f6',
};
const info = ref({
    product: {}
})
const currentRate = ref(100)
const text = ref('拼团进度: 100%')
const time = ref(30 * 60 * 60 * 1000)
const teamlist = ref([])

const currentProId = ref(0)

// sku属性
const SkuRef = ref(null)
const SkuShow = ref(false)
const sku = ref({})
const goods = ref({})
const properties = ref([])
const detail = ref({})

onBeforeMount(() => {
    getIndexData()
})

const getIndexData = async () => {
    let result = await Api.TeamInfo({
        teamid: teamid
    })
    if (result.code == 1) {
        info.value = result.data.teaminfo
        teamlist.value = result.data.teamlist

        // 进度条
        currentRate.value = teamlist.value.length * 100 / info.value.total

        // 进度条文字
        text.value = `拼团进度: ${currentRate.value}%`

        // 倒计时
        let createtime = parseFloat(Date.now() / 1000)
        time.value = (info.value.endtime - createtime) * 1000
    }
}

// 获取商品详情
const getProductInfoData = async () => {
    SkuShow.value = true;
    let result = await Api.ProductInfo({
        proid: info.value.product.id,
        busid: LoginUser.id ?? 0
    })
    
    currentProId.value = info.value.product.id;

    if (result.code == 1) {
        let ProductData = result.data.info
        let SkuData = result.data.sku
        let PropertiesData = result.data.properties

        detail.value = ProductData
        sku.value = SkuData
        properties.value = Object.values(PropertiesData)
        goods.value = {
            picture: detail.value.thumbs_text
        }
    }
}

// 参与拼团
const teamJoin = () =>
{
    SkuShow.value = false;

    if(JSON.stringify(LoginUser) == '{}') {
        toast({
            message: '未登陆，请先去登陆',
            onClose: () =>{
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    // 通过 ref 可以获取到 Sku 实例并调用实例方法，详见组件实例方法。
    let SkuData = SkuRef.value.getSkuData()

    const selectedNum = SkuData.selectedNum

    if(selectedNum <= 0)
    {
        error('数量不能为小于0');
        return false
    }

    //判断是否有选择规格
    if(properties.value.length > 0 && !SkuData.selectedSkuComb)
    {
        error('请选择商品规格')
        return false;
    }

    let relationids = []

    if(properties.value.length > 0)
    {
        let  properties = SkuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if(item.v)
            {
                var id = item.v[0] ? item.v[0].id : 0;
                relationids.push({
                    id: id,
                    name: item.v[0].name ?? '',
                    price: item.v[0].price,
                    teamid: teamid,
                })
            }
        })
    }

    // 存储属性数据
    proxy.$cookies.set('relationids', JSON.stringify(relationids))

    //路由跳转
    proxy.$router.push({
        path: '/team/add',
        query:{
            proid: currentProId.value,
            nums: selectedNum,
            isJoin: 1
        }
    })
}

</script>
<style scoped>
.box {
    width: 100%;
    padding-top: 20px;
    text-align: center;
}

:deep(.van-circle__text) {
    font-size: 20px;
}

.box_time {
    font-size: 20px;
    text-align: center;
    line-height: 45px;
}

:deep(.van-count-down) {
    font-size: 20px;
    text-align: center;
    line-height: 45px;
}

.item {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    align-content: center;
    padding-left: 10px;
    margin-bottom: 10px;
    margin-top: 10px;
}

.item .info {
    margin-left: 10px;
}

.item .info .nickname,
.item .info .time {
    font-size: 16px;
    font-weight: bold;
}

.actions {
    position: fixed;
    width: 100%;
    left: 0;
    bottom: 0;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    align-content: center;
}

.van-button {
    border-radius: 0;
}
</style>